package com.wjj.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wjj.dto.StudentDTO;
import com.wjj.service.StudentService;
import java.util.Arrays;
import java.util.List;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author junjun Wang
 * @Date Create in 22:58 2023/12/6
 **/
@RestController
@Slf4j
public class StudentController {

	@Autowired
	private StudentService studentService;

	@GetMapping("/all")
	public List<StudentDTO> getStudents() {
		log.info("service 2");
		return studentService.getStudents();
	}

	@GetMapping("/get/{studentId}")
	public StudentDTO getStudentById(@PathVariable("studentId") @NotNull Integer studentId) {
		return studentService.getStudentById(studentId);
	}

	@PostMapping("/add")
	public void addStudent(@RequestBody @NotEmpty List<StudentDTO> students) {
		studentService.addStudent(students);
	}

	@PutMapping("/update")
	public void updateStudent(@RequestBody @NotNull StudentDTO student) {
		studentService.updateStudent(student);
	}

	@DeleteMapping("/delete/{studentId}")
	public void deleteStudentById(@PathVariable("studentId") @NotNull Integer studentId) {
		studentService.deleteStudentById(studentId);
	}

	@GetMapping("/get-student/{classId}")
	@HystrixCommand(fallbackMethod = "getStudentByClassIdHystrix")
	public List<StudentDTO> getStudentByClassId(@PathVariable("classId") @NotNull Integer classId) {
		List<StudentDTO> studentDTOS = studentService.getStudentByClassId(classId);
		if (CollectionUtils.isEmpty(studentDTOS)) {
			throw new RuntimeException("Get Empty Students");
		}
		return studentDTOS;
	}

	public List<StudentDTO> getStudentByClassIdHystrix(
			@PathVariable("classId") @NotNull Integer classId) {
		return Arrays.asList(StudentDTO.builder()
				.studentId(0)
				.studentName("Hystrix Student")
				.build());
	}

}
